#include <iostream>
#include <unistd.h>
#include <pthread.h>

#define NUM 5

int cnt = 100;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *pthread(void *arg)
{
    char *name = static_cast<char *>(arg);

    while (true)
    {
        pthread_mutex_lock(&lock);

        // 线程进入wait，进行等待(信号变量满足条件)，这时候把解锁，让其他进程能够进来。
        // 如果信号变量满足条件，那么该线程从当前wait开始运行并且重新加锁
        // 如果被唤醒了，但是申请锁失败，那么就会在锁这里进行等待
        pthread_cond_wait(&cond, &lock);

        std::cout << name << ":" << cnt << std::endl;
        cnt--;

        pthread_mutex_unlock(&lock);
    }

    return nullptr;
}

int main()
{
    pthread_t rid;
    for (int i = 0; i < NUM; i++)
    {
        char *id = new char[64];
        // snprintf(id,sizeof(id),)
        snprintf(id, 64, "thread-%d", i);
        int n = pthread_create(&rid, nullptr, pthread, id);
        if (n != 0)
            continue;
    }
    while (true)
    {
        std::cout << "main" << std::endl;
        // 唤醒线程  ->  单个线程
        //pthread_cond_signal(&cond);

        // 唤醒所有线程
        pthread_cond_broadcast(&cond);
        sleep(1);
    }

    return 0;
}
